﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IOperation;

namespace _00_反射_计算器
{
    public partial class Form1 : Form
    {
        List<ClassLibarayInfo> classLibarayInfos = new List<ClassLibarayInfo>();
        public Form1()
        {
            InitializeComponent();
            //=======================遍历文件夹下的动态链接库=======================//
            //获取指定文件夹的下的所有文件
            DirectoryInfo directoryInfo = new DirectoryInfo("./Tool");
            //遍历路径下的所有文件
            foreach (FileInfo item in directoryInfo.GetFiles("*.dll"))
            {
                //加载动态链接库
               Assembly assembly = Assembly.LoadFrom(item.FullName);
                //获取动态链接库中的所有类
                Type[] types = assembly.GetTypes();
                //遍历所有类
                foreach (Type type in types)
                {
                    //创建类的实例
                    Operation operation = (Operation)Activator.CreateInstance(type);
                    //获取类的名称添加到下拉框中
                    comboBox1.Items.Add(operation.Name);
                    //保存遍历到的信息:类的名称，动态链接库的路径， 类的完整名称
                    ClassLibarayInfo info = new ClassLibarayInfo();
                    info.Name = operation.Name;
                    info.ClassFullName = type.FullName;
                    info.DllPath = item.FullName;
                    //添加到集合当中
                    classLibarayInfos.Add(info);
                }
            }
        }
        /// <summary>
        /// 计算按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //获取当前选中的内容
            string type = this.comboBox1.SelectedItem.ToString();
            //在List当中查询到对应的对象
            ClassLibarayInfo info = classLibarayInfos.Find(t => t.Name == type);
            //拿到 动态链接库路径 | 类的名称
            Operation operation = (Operation)Assembly.LoadFrom(info.DllPath).CreateInstance(info.ClassFullName);
            //对属性进行赋值
            operation.NumberA = this.textBox1.Text;
            operation.NumberB = this.textBox2.Text;
            //调用方法计算结果
            this.textBox3.Text = operation.GetResult().ToString();
            //释放对象
            operation = null;
        }
    }
}
